package com.yingpai.fitness.dvp_2_0.common.finalokgo.request;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.util.Log;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.util.GsonUtil;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.TypeTake;
import com.yingpai.fitness.dvp_2_0.main.util.Util;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.entity.wx.TokenBean;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by ASUS on 2018/11/1.
 */

public class FinalOkgo {

    protected Context context;
    private List<String> keyList = new ArrayList<>();


    public FinalOkgo(Context context) {
        this.context = context;
    }

    /**
     * @param method
     * @param url
     * @param params
     * @param tag
     * @param callback
     * @description 普通请求
     */
    public void request(String method, String url, @Nullable HttpParams params, String tag, Callback callback) {
        if (params == null) {
            params = new HttpParams();
        }
        switch (method) {
            case RequestType.GET:
                get(url, tag, callback);
                break;
            case RequestType.GETLIST:
                getList(url, tag, callback);
                break;
            case RequestType.POST:
                post(url, params, tag, callback);
                break;
            case RequestType.POSTLIST:
                postList(url, params, tag, callback);
                break;
            case RequestType.POSTFILE:
                postFile(url, params, tag, callback);
                break;
        }
    }

    /**
     * @param method
     * @param url
     * @param params
     * @param tag
     * @param callback
     * @description 加密请求
     */
    public void requestEncrypt(String method, String url, @Nullable HashMap<String, Object> params, String tag, Callback callback) {
        if (params == null) {
            params = new HashMap<>();
        }
        switch (method) {
            case RequestType.POSTENCRYPT:
                postEncrypt(url, params, tag, callback);
                break;
            case RequestType.POSTFILESENCRYPT:
                postFilesEncrypt(url, params, tag, callback);
                break;
            case RequestType.GETENCRYPT:
                getEncrypt(url, params, tag, callback);
                break;
        }
    }

    private void get(String url, String tag, final Callback callback) {
        OkGo.<String>get(url)
                .tag(tag)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Logger.e("success:" + response.body());
                        try {
                            callback.onSuccess(parse(response.body(), TypeTake.getClass(callback)));
                        } catch (Exception e) {
                            Logger.e("exception:" + e.getMessage());
                            callback.onPaseException(e);
                            callback.onError(response);
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        callback.onError(response);
                    }
                });
    }

    private void getList(String url, String tag, final Callback callback) {
        OkGo.<String>get(url)
                .tag(tag)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Logger.e("success:" + response.body());
                        try {
                            callback.onListSuccess(parseList(response.body(), TypeTake.getClass(callback)));
                        } catch (Exception e) {
                            Logger.e("exception:" + e.getMessage());
                            callback.onPaseException(e);
                            callback.onError(response);
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        callback.onError(response);
                    }
                });
    }

    private void post(String url, HttpParams params, String tag, final Callback callback) {
        OkGo.<String>post(url)
                .tag(tag)
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Logger.e("success:" + response.body());
                        try {
                            callback.onSuccess(parse(response.body(), TypeTake.getClass(callback)));
                        } catch (Exception e) {
                            Logger.e("exception:" + e.getMessage());
                            callback.onPaseException(e);
                            callback.onError(response);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        callback.onError(response);
                    }
                });
    }

    private void postFile(String url, HttpParams params, String tag, final Callback callback) {
        OkGo.<String>post(url)
                .isMultipart(true)
                .tag(tag)
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Logger.e("success:" + response.body());
                        try {
                            callback.onSuccess(parse(response.body(), TypeTake.getClass(callback)));
                        } catch (Exception e) {
                            Logger.e("exception:" + e.getMessage());
                            callback.onPaseException(e);
                            callback.onError(response);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        callback.onError(response);
                    }
                });
    }

    private void postList(String url, HttpParams params, String tag, final Callback callback) {
        OkGo.<String>post(url)
                .tag(tag)
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Logger.e("success:" + response.body());
                        try {
                            callback.onListSuccess(parseList(response.body(), TypeTake.getClass(callback)));
                        } catch (Exception e) {
                            Logger.e("exception:" + e.getMessage());
                            callback.onPaseException(e);
                            callback.onError(response);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        callback.onError(response);
                    }
                });
    }

    private void postEncrypt(String url, HashMap<String, Object> params, String tag, final Callback callback) {
        keyList.clear();
        String timeString = Long.toString(System.currentTimeMillis());
        String token = ((TokenBean) (SharedPreferencesHelp.getBean(Constant.TOKENBEAN))).getToken();
        params.put("timestamp", timeString);
        params.put("token", token);
        HttpParams httpParams = new HttpParams();
        for (String key : params.keySet()) {
            Object obj = params.get(key);
            httpParams.put(key, String.valueOf(obj));
            if (key.startsWith("__")) {
                keyList.add(key);
            }
        }
        for (int i = 0; i < keyList.size(); i++) {
            params.remove(keyList.get(i));
        }
        httpParams.put("sign", Util.general(params));
        OkGo.<String>post(url)
                .tag(tag)
                .params(httpParams)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Logger.e("success:" + response.body());
                        Log.e("ss","response="+response);
                        try {
                            callback.onSuccess(parse(response.body(), TypeTake.getClass(callback)));
                        } catch (Exception e) {
                            Logger.e("exception:" + e.getMessage());
                            callback.onPaseException(e);
                            callback.onError(response);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Logger.e("error:" + response.message());
                        callback.onError(response);
                    }
                });
    }

    private void postFilesEncrypt(String url, HashMap<String, Object> params, String tag, final Callback callback) {
        keyList.clear();
        String timeString = Long.toString(System.currentTimeMillis());
        String token = ((TokenBean) (SharedPreferencesHelp.getBean(Constant.TOKENBEAN))).getToken();
        params.put("timestamp", timeString);
        params.put("token", token);
        HttpParams httpParams = new HttpParams();
        for (String key : params.keySet()) {
            Object obj = params.get(key);
            if (key.startsWith("__files")) {
                httpParams.putFileParams(key, (List<File>) obj);
            } else if (key.startsWith("__file")) {
                httpParams.put(key, (File) obj);
            } else {
                httpParams.put(key, String.valueOf(obj));
            }
            if (key.startsWith("__")) {
                keyList.add(key);
            }
        }
        for (int i = 0; i < keyList.size(); i++) {
            params.remove(keyList.get(i));
        }
        httpParams.put("sign", Util.general(params));
        OkGo.<String>post(url)
                .isMultipart(true)
                .tag(tag)
                .params(httpParams)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Logger.e("success:" + response.body());
                        try {
                            callback.onSuccess(parse(response.body(), TypeTake.getClass(callback)));
                        } catch (Exception e) {
                            Logger.e("exception:" + e.getMessage());
                            callback.onPaseException(e);
                            callback.onError(response);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Logger.e("error:" + response.message());
                        callback.onError(response);
                    }
                });
    }

    private void getEncrypt(String url, HashMap<String, Object> params, String tag, final Callback callback) {
        keyList.clear();
        String timeString = Long.toString(System.currentTimeMillis());
        String token = ((TokenBean) (SharedPreferencesHelp.getBean(Constant.TOKENBEAN))).getToken();
        params.put("timestamp", timeString);
        params.put("token", token);
        HttpParams httpParams = new HttpParams();
        for (String key : params.keySet()) {
            Object obj = params.get(key);
            httpParams.put(key, String.valueOf(obj));
            if (key.startsWith("__")) {
                keyList.add(key);
            }
        }
        for (int i = 0; i < keyList.size(); i++) {
            params.remove(keyList.get(i));
        }
        httpParams.put("sign", Util.general(params));
        OkGo.<String>get(url)
                .tag(tag)
                .params(httpParams)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Logger.e("success:" + response.body());
                        try {
                            callback.onSuccess(parse(response.body(), TypeTake.getClass(callback)));
                        } catch (Exception e) {
                            Logger.e("exception:" + e.getMessage());
                            callback.onPaseException(e);
                            callback.onError(response);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        callback.onError(response);
                    }
                });
    }

    private Object parse(String json, Class type) {
        Object obj = GsonUtil.jsonStringToClassWithGson(json, type);
        return obj;
    }

    private List<Object> parseList(String json, Class type) {
        List<Object> list = GsonUtil.jsonToList(json, type);
        return list;
    }

    public void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(context, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        ActivityCompat.startActivity(context, intent, ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) context).toBundle());
    }

    public void startActivity(Class<?> cls) {
        Intent intent = new Intent(context, cls);
        ActivityCompat.startActivity(context, intent, ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) context).toBundle());
    }

    public void startFinishActivity(Class<?> cls) {
        Intent intent = new Intent(context, cls);
        context.startActivity(intent);
        ((Activity) context).finish();
    }

    public void startFinishActivity(Class<?> cls, @Nullable Bundle bundle) {
        Intent intent = new Intent(context, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        context.startActivity(intent);
        ((Activity) context).finish();
    }

    public void finish() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ((Activity) context).finishAfterTransition();
        } else {
            ((Activity) context).finish();
        }
    }
}
